//
//  DrugViewController.m
//  TestARC
//
//  Created by wuxiaoquan on 12-9-22.
//  Copyright (c) 2012年 wuxiaoquan. All rights reserved.
//

#import "BaseSearchViewController.h"

#define CommonViewTAG 100
#define SeggestionViewTAG 101

@interface BaseSearchViewController ()

@end

@implementation BaseSearchViewController

@synthesize searchBar;
@synthesize hipLabel,commonTableView,seggestionTableView,dbHelper,overlayView;
@synthesize commonArray,seggestionArray;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.dbHelper = [[DBHelper alloc]init];
    if ([dbHelper open]) {
        //NSLog(@"open db ok!");
    } else {
         NSLog(@"can not open db!");
    }
    self.commonArray = [NSMutableArray arrayWithCapacity:100];
    self.seggestionArray = [NSMutableArray arrayWithCapacity:10];
    
    //为黑色蒙版添加手势识别，并且先移除蒙版
    UITapGestureRecognizer *_oneFingerTaps = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchOverlay:)];
    _oneFingerTaps.numberOfTapsRequired = 1;
    _oneFingerTaps.numberOfTouchesRequired = 1;
    [self.overlayView addGestureRecognizer:_oneFingerTaps];
    [self.overlayView removeFromSuperview];
    showOverlayView = false;
    //为建议列表添加手势识别，首先移除建议列表
//    UITapGestureRecognizer *_oneFingerTapsForSeggest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard:)];
//    _oneFingerTaps.numberOfTapsRequired = 1;
//    _oneFingerTaps.numberOfTouchesRequired = 1;
//    [self.seggestionTableView addGestureRecognizer:_oneFingerTapsForSeggest];
    [self.seggestionTableView removeFromSuperview];
    showSeggestView = false;
    //设置常用列表
    [self setCommonView];
    
    //设置searchBar键盘
    for(UIView *subView in self.searchBar.subviews) {
        if([subView conformsToProtocol:@protocol(UITextInputTraits)]) {
            [(UITextField *)subView setKeyboardAppearance: UIKeyboardAppearanceAlert];
            [(UITextField *)subView setReturnKeyType:UIReturnKeyDone];
        }
    }
    //设置searchBar的取消按钮为消失
    [self.searchBar setShowsCancelButton:false animated:YES];
    //设置显示顶部bar
    [self.navigationController setNavigationBarHidden:FALSE animated:YES];
    [self addRoundBound:self.commonTableView];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    [self.dbHelper close];
    self.dbHelper = nil;
    self.searchBar = nil;
    self.hipLabel = nil;
    self.commonTableView = nil;
    self.seggestionTableView = nil;
    self.commonArray = nil;
    self.seggestionArray = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
//--------------------------获得列表数据-------------------------------
-(void)loadCommonData
{
    
}

-(void)setCommonView
{
    [self loadCommonData];
    //NSLog(@"common data count = %d",[self.commonArray count]);
    [self.commonTableView reloadData];
}

-(void)loadSeggestionData:(NSString *)queryText
{
    
}
-(void)setSeggestionView:(NSString *)queryText
{
    [self loadSeggestionData:queryText];
    //NSLog(@"seggestion data count = %d",[self.seggestionArray count]);
    [self.seggestionTableView reloadData];
}

//-----------------列表委托函数，数据填充--------------------------------
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if([tableView tag]==CommonViewTAG)
    {
        return [self.commonArray count];
    }
    else
    {
        return [self.seggestionArray count];
    }
}
-(void)setCellImage:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CommonTableIdentifier = @"CommonTableIdentifier";
    static NSString *SeggestionTableIdentifier = @"SeggestionTableIdentifier";
    UITableViewCell *cell = nil;
    NSInteger row;
    if (tableView.tag == CommonViewTAG) {
        cell = [tableView dequeueReusableCellWithIdentifier:CommonTableIdentifier];
        if (cell==nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
                                         reuseIdentifier:CommonTableIdentifier];
        }
        row = [indexPath row];
        //NSLog(@"commArray at %d:%@",row,[commonArray objectAtIndex:row]);
        cell.textLabel.text = [[commonArray objectAtIndex:row]objectForKey:@"name"];
        
    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:SeggestionTableIdentifier];
        if (cell==nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
                                         reuseIdentifier:SeggestionTableIdentifier];
        }
        row = [indexPath row];
        
        cell.textLabel.text = [[seggestionArray objectAtIndex:row]objectForKey:@"name"];
        [self setCellImage:cell forRowAtIndexPath:indexPath];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.font = [UIFont systemFontOfSize:17.0f];
    return cell;
}

-(IBAction)dismissKeyboard:(id)sender
{
    [self.searchBar resignFirstResponder];
    UIButton * btn = [self getSearchBarCancelButton];
    [btn setEnabled:YES];
}
//-----------------本地搜索代码-----------------------------
-(void)startSearch
{
    //NSLog(@"begin search!");
    //[self.navigationController setNavigationBarHidden:TRUE animated:YES];
    if (showOverlayView) {
        
    } else {
        [self.view addSubview:self.overlayView];
        
        CGRect overylayFrame = self.overlayView.frame;
        float overylayX = overylayFrame.origin.x;
        float overylayY = overylayFrame.origin.y;
        float overylayWidth = self.view.frame.size.width;
        float overylayHight = self.view.frame.size.height - overylayY;
        self.overlayView.frame = CGRectMake(overylayX, overylayY, overylayWidth, overylayHight);
        
        showOverlayView = true;
    }
    [self.searchBar setShowsCancelButton:true animated:YES];
    [self searchForText:self.searchBar.text];
}

-(void)endSearch
{
    //NSLog(@"end search!");
    [self.navigationController setNavigationBarHidden:FALSE animated:YES];
    [self.overlayView removeFromSuperview];
    showOverlayView = false;
    [self.seggestionTableView removeFromSuperview];
    showSeggestView = false;
    self.searchBar.text = @"";
    [self.searchBar resignFirstResponder];
    [self.searchBar setShowsCancelButton:false animated:YES];
    //[self.seggestionTableView resignFirstResponder];
}
-(void)searchForText:(NSString *)queryText
{
    //NSLog(@"text:%@",queryText);
    if ([queryText length]<1&&showSeggestView) {
        [self.seggestionTableView removeFromSuperview];
        showSeggestView = false;
    }
    else if([queryText length ]>=1 && !showSeggestView){
        [self.view addSubview:self.seggestionTableView];
        
        CGRect overylayFrame = self.seggestionTableView.frame;
        float overylayX = overylayFrame.origin.x;
        float overylayY = overylayFrame.origin.y;
        float overylayWidth = self.view.frame.size.width;
        float overylayHight = self.view.frame.size.height - overylayY;
        self.seggestionTableView.frame = CGRectMake(overylayX, overylayY, overylayWidth, overylayHight);
        
        showSeggestView = true;
    }
    if ([queryText length]>=1) {
        [self setSeggestionView:queryText];
    }
    
}
-(IBAction)touchOverlay:(id)sender
{
    [self endSearch];
}


//------------------搜索相关代码---------------------------

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [self startSearch];
    //[self changeCancelButton];
}

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    //NSLog(@"end edit text!");
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [self searchForText:searchText];
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    //NSLog(@"cancel search!");
    [self endSearch];
    //[self backToMain];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self dismissKeyboard:nil];
}

-(UIButton *)getSearchBarCancelButton{
    UIButton* btn=nil;
    for(UIView* v in self.searchBar.subviews) {
        if ([v isKindOfClass:UIButton.class]) {
            btn=(UIButton*)v;
            break;
        }
    }
    return btn;
}
-(void)changeCancelButton
{
    UIButton *button = [self getSearchBarCancelButton];

    [button setTitle:@"" forState:UIControlStateNormal];
    [button setTitle:@"" forState:UIControlStateSelected];
    [button setImage:[[UIImage imageNamed:@"logo_y_normal_30.png"]stretchableImageWithLeftCapWidth:0.0 topCapHeight:0.0] forState:UIControlStateNormal];
    [button setImage:[[UIImage imageNamed:@"logo_y_select_30.png"]stretchableImageWithLeftCapWidth:0.0 topCapHeight:0.0] forState:UIControlStateSelected];
    [self.searchBar layoutSubviews];
}
//------------------------
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self dismissKeyboard:scrollView];
}

@end
